package com.mlink.vs.action;

import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.seasar.struts.annotation.Execute;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.mlink.vs.entity.ChatMsgListResult;
import com.mlink.vs.entity.PiccMessage;
import com.mlink.vs.service.PiccMessageService;
import com.mlink.vs.util.StreamUtil;

/**
 * 聊天消息相关接口
 * @author Administrator
 */
public class ChatMsgAction {

	/**
	 * request请求对象
	 */
	@Resource
	private HttpServletRequest req;

	/**
	 * response请求对象
	 */
	@Resource
	private HttpServletResponse rep;

	@Resource
	PiccMessageService piccMessageService;

	// 添加消息
//	{
//	"type":"photo", (photo 拍照 ,message 文字消息,muted 声音[message 为 "true" 禁音 "false" 启动声音])
//	"message":"photo"
//	}
	@Execute(validator = false)
	public String addMsg() {
		Gson gson = new Gson();
		StringBuffer indata = StreamUtil.getRequestBody(req);
		
         System.out.println("addMsg--"+indata.toString());

		try {
			String room = null;
			String user = null;
			String to = null;
			String message = null;
			JSONObject jsonObject =  new JSONObject(indata.toString());
			String action  = jsonObject.getString("action");
		
			if(action.equals("message")) {
				JSONObject params  = jsonObject.getJSONObject("params");
				room = params.getString("room");
		
				if(params.isNull("to")==false) {
					to =  params.getString("to");
				}
				user = params.getString("user");
				message = params.getString("message");
				JSONObject messaget =  new JSONObject(message);
				String type =  messaget.getString("type");
				if(type.equals("message")) {
					JSONObject message1=  messaget.getJSONObject("message");
					String type1 = message1.getString("type");
					String info = message1.getString("info");
					
					SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					String signinDate = formatter.format(new Timestamp((new Date()).getTime()));
					PiccMessage piccMsg = new PiccMessage();
					piccMsg.id = UUID.randomUUID().toString().replace("-", "");
		
					piccMsg.senderId = user;
					piccMsg.receiverId = to;
					
					piccMsg.signinDate = signinDate;
					piccMsg.isRead = "0";
					piccMsg.content = info;
					piccMsg.msgType =type1;
					piccMessageService.insert(piccMsg);
					
					Map<String, String> stsMap = new HashMap<String, String>();
					stsMap.put("sts", "0");
					rep.setCharacterEncoding("utf-8");
					rep.getWriter().println(gson.toJson(stsMap));
					rep.getWriter().flush();
					
				}
			
			}
			
		} catch (JSONException e) {
			//e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		Map<String, String> stsMap = new HashMap<String, String>();
		GsonBuilder gb =new GsonBuilder();
		gb.disableHtmlEscaping();
		gb.create().toJson("http://www.baidu.com/id=1");
		gb.create().toJson(stsMap);
       return null;

	}
//
//	// 获取和某人的聊天记录
	@Execute(validator = false)
	public String getChatMsgRecord() {
		Gson gson = new Gson();
		StringBuffer indata = StreamUtil.getRequestBody(req);
		Map<String, String> stsMap = new HashMap<String, String>();
		Map<String, String> mapData = gson.fromJson(indata.toString(), Map.class);
		String userId1 = null;
		String userId2 = null;
		String pageNumStr = null;
		String pageCountStr = null;
		if (mapData != null) {
			userId1 = (String) mapData.get("userId1");
			userId2 = (String) mapData.get("userId2");
			pageNumStr = (String) mapData.get("pageNum");
			pageCountStr = (String) mapData.get("pageCount");
		}
		try {

			Boolean isBlank = false;
			rep.setCharacterEncoding("utf-8");
			if (StringUtils.isBlank(userId1)) {
				stsMap.put("sts", "1");
				stsMap.put("msg", "userId1不能为空");
				isBlank = true;
			}
			if (StringUtils.isBlank(userId2)) {
				stsMap.put("sts", "1");
				stsMap.put("msg", "userId2不能为空");
				isBlank = true;
			}
			if (StringUtils.isBlank(pageNumStr)) {
				stsMap.put("sts", "1");
				stsMap.put("msg", "pageNum不能为空");
				isBlank = true;
			}
			if (StringUtils.isBlank(pageCountStr)) {
				stsMap.put("sts", "1");
				stsMap.put("msg", "pageCount不能为空");
				isBlank = true;
			}

			if (isBlank == true) {
				stsMap.put("sts", "1");
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;
			}

			int pageNum = Integer.parseInt(pageNumStr);
			int pageCount = Integer.parseInt(pageCountStr);
			
			int startt = (pageNum- 1) * pageCount;
			
			List<PiccMessage> pm = piccMessageService.findAllbyId(userId1, userId2, startt, pageCount);
			int totalCount = piccMessageService.findTotalCount(userId1, userId2);
			
			String sumPage = null;
			if (totalCount % pageCount == 0) {
				sumPage = totalCount / pageCount+"";
			} else {
				sumPage =  totalCount / pageCount + 1+"";
			}
			
			ChatMsgListResult clr = new ChatMsgListResult();
			clr.sumPage = sumPage;
			clr.totalCount = totalCount + "";
			clr.sts = "0";
			clr.list = pm;
	
			rep.setCharacterEncoding("utf-8");
			rep.getWriter().println(gson.toJson(clr));
			rep.getWriter().flush();

		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}
	// 查询消息记录
	@Execute(validator = false)
	public String queryMsgRecord() {
		Gson gson = new Gson();
		StringBuffer indata = StreamUtil.getRequestBody(req);
		Map<String, String> stsMap = new HashMap<String, String>();
		Map<String, String> mapData = gson.fromJson(indata.toString(), Map.class);
		
		String pageNumStr = null;
		String pageCountStr = null;
		String appId = null;
		String sertId = null;
		String keywords = null;
		String msgType = null;
		String startDate = null;
		String endDate = null;
		if (mapData != null) {
			pageNumStr = (String) mapData.get("pageNum");
			pageCountStr = (String) mapData.get("pageCount");
			appId = (String) mapData.get("appId");
			sertId = (String) mapData.get("sertId");
			keywords = (String) mapData.get("keywords");
			msgType = (String) mapData.get("msgType");
			startDate = (String) mapData.get("startDate");
			endDate = (String) mapData.get("endDate");
		}
		
		try {

			Boolean isBlank = false;
			rep.setCharacterEncoding("utf-8");
			if (StringUtils.isBlank(pageNumStr)) {
				stsMap.put("sts", "1");
				stsMap.put("msg", "pageNum不能为空");
				isBlank = true;
			}
			if (StringUtils.isBlank(pageCountStr)) {
				stsMap.put("sts", "1");
				stsMap.put("msg", "pageCount不能为空");
				isBlank = true;
			}
			if (isBlank == true) {
				stsMap.put("sts", "1");
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;
			}

			int pageNum = Integer.parseInt(pageNumStr);
			int pageCount = Integer.parseInt(pageCountStr);
			int startt = (pageNum- 1) * pageCount;
			List<PiccMessage> pm = piccMessageService.queryAllbyId(appId, sertId, msgType, keywords, startDate, endDate, startt, pageCount);
			int totalCount = piccMessageService.totalCountQueryAllbyI(appId, sertId, msgType, keywords, startDate, endDate);
		    String sumPage = null;
		    
			if (totalCount % pageCount == 0) {
				sumPage = totalCount / pageCount+"";
			} else {
				sumPage =  totalCount / pageCount + 1+"";
			}
			ChatMsgListResult clr = new ChatMsgListResult();
			clr.sts = "0";
			clr.list = pm;
			clr.sumPage = sumPage;
			clr.totalCount = totalCount+"";
			
			rep.setCharacterEncoding("utf-8");
			rep.getWriter().println(gson.toJson(clr));
			rep.getWriter().flush();

		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}

}